<template>
  <iframe id="iframe" name="previewIframe" :src="src" frameborder="0"></iframe>
</template>

<script>
import { formatDate, api } from '~/assets/utils'

export default {
  data() {
    return {
      src: `/upload/${this.$route.query.id}/index.html`,
      currentDate: formatDate(new Date(), 'yyyy-MM-dd hh:mm')
    }
  },
  methods: {
    async appendNotes(pageDocument) {
      const result = await this.$axios.get(api.labelList, {
        params: {
          pageName: pageDocument.title
        }
      })
      let notes = ''
      result.data.forEach(item => {
        notes += `
            <div class="note-wrap" id=${item.id}  style="left:${item.left};top:${item.top};">
              <div class="button-wrap">
                <input class="edit-btn" type="button" value="编辑"/>
                <input class="del-btn" type="button" value="删除"/>
                <input class="entry-btn" type="button" value="保存"/>
              </div>
              <div class="input-wrap">
                <div class="input" contenteditable="false">${item.label}</div>
              </div>
            </div>
        `
      })
      $(pageDocument).find('body').append(notes)
    },
    appendStyle(pageDocument) {
      const style = `<style>
              .note-wrap{
                position:absolute;
                padding:0;       
              }
              .input-wrap{
                border:1px solid #111;
                border-radius:0 0 6px 6px;
                background:#f1f1f1;
                min-width:120px;
                max-width:200px;
              }
              .input.active{
                border:1px solid red;
              }
              .note-wrap .input{
                outline:none;
                font-size:12px;
                padding:3px 5px;
                background:#fff;
                margin:5px;
                border-radius:6px;
              }
              .button-wrap{
                clear:both;
                height:20px;
              }
              .button-wrap input{
                color:#fff;
                border:none;
                font-size:12px;
                padding:2px 5px;
                outline:none;
                cursor: pointer;
                float:left;
                background:#aaa;
              }
              .button-wrap .del-btn{
                background:red;
              }
              .button-wrap .entry-btn{
                background:blue;
              }
              .button-wrap .button-wrap{
                clear:both;
                text-align:right;
                padding:0 0 5px 0;
              }
            </style>`
      $(pageDocument).find('body').append(style)
    },
    init(pageDocument) {
      const _this = this
      $(pageDocument).on('dblclick', function (e) {
        const target = $(e.target)
        if (target.is('.input')) {
          target.addClass('active').attr('contenteditable', true)
        }
        if (target.parents().is('.note-wrap')) {
          return
        }

        const note = `
            <div class="note-wrap"  style="left:${e.pageX}px;top:${e.pageY}px;">
              <div class="button-wrap">
                <input class="edit-btn" type="button" value="编辑"/>
                <input class="del-btn" type="button" value="删除"/>
                <input class="entry-btn" type="button" value="保存"/>
              </div>
              <div class="input-wrap">
                <div class="input" contenteditable="false">我是可编辑的标注</div>
              </div>
            </div>
        `
        $(pageDocument).find('body').append(note)
      })

      $(pageDocument).on('keydown', 'body', function (e) {
        // const $parent = $(this).parents('.note-wrap')
        const keyNum = e.which // 获取键值
        const target = $(e.target)
        if (target.parents().is('.input-wrap')) {
          return
        }
        $(this).find('.note-wrap').each(function () {
          if ($(this).find('.input').hasClass('active')) {
            switch (keyNum) { // 判断按键
              case 38: $(this).animate({ top: '-=5px' }, 50); break
              case 39: $(this).animate({ left: '+=5px' }, 50); break
              case 40: $(this).animate({ top: '+=5px' }, 50); break
              case 37: $(this).animate({ left: '-=5px' }, 50); break
              default:
                break
            }
          }
        })
        return false
      })
      $(pageDocument).on('click', '.note-wrap .edit-btn', function () {
        const $parent = $(this).parents('.note-wrap')
        const flag = $parent.find('.input').attr('contenteditable') == 'true'
        $parent.find('.input').toggleClass('active').attr('contenteditable', !flag)
      })

      $(pageDocument).on('click', '.note-wrap .del-btn', async function () {
        const $parent = $(this).parents('.note-wrap')
        const id = $parent.attr('id')
        if (id) {
          await _this.$axios.post(api.delLabel, { id })
          $parent.remove()
        } else {
          $parent.remove()
        }
      })
      $(pageDocument).on('click', '.note-wrap .entry-btn', async function () {
        const $parent = $(this).parents('.note-wrap')
        const id = $parent.attr('id')
        const pageName = pageDocument.title
        const projectId = _this.$route.query.id
        const left = $parent.css('left')
        const top = $parent.css('top')
        const label = $parent.find('.input').html()
        if (id) {
          await _this.$axios.post(api.updateLabel, { id, pageName, projectId, left, top, label })
        } else {
          await _this.$axios.post(api.addLabel, { pageName, projectId, left, top, label })
        }
        _this.$message({
          type: 'success',
          message: '操作成功!'
        })
        $parent.find('.input').removeClass('active').attr('contenteditable', false)
      })
      $(pageDocument).on('click', 'body', function (e) {
        const target = $(e.target)
        if (!target.parents().is('.input-wrap') && !target.parents().is('.button-wrap')) {
          $(pageDocument).find('.input').removeClass('active').attr('contenteditable', false)
        }
      })
    }
  },
  mounted() {
    const _this = this
    const iframe = $('#iframe')[0]
    $(iframe).on('load', () => {
      const page = $(iframe.contentDocument).find('#mainFrame')[0]
      const pageDocument = page.contentDocument
      _this.appendStyle(pageDocument)
      _this.appendNotes(pageDocument)
      _this.init(pageDocument)
      $(page).on('load', e => {
        const page = $(iframe.contentDocument).find('#mainFrame')[0]
        const pageDocument = page.contentDocument
        _this.appendStyle(pageDocument)
        _this.appendNotes(pageDocument)
        _this.init(pageDocument)
        // alert(pageDocument.title)
      })
    })
  }
}
</script>

<style lang='scss'>
iframe {
  width: 100%;
  height: 100%;
  border: none;
}
</style>
